extends Control

var merchant

func _ready():
	GlobalSignal.showWeaponShop.connect(openWeaponShop)


func openWeaponShop(shopItems, merchant):
	self.merchant = merchant
	$Control.modulate.a = 1
	
	for child in $Control/Bg.get_children():
		child.queue_free()
	
	var itemCount = shopItems.keys().size()
	$Control/Bg.size.y = 32 * itemCount
	
	
	var count = 0
	for itemResName in shopItems.keys():
		var itemPrice = shopItems[itemResName]
		
		var shopItemRes = Global.sceneFileDict["shopItem"]
		var shopItem = shopItemRes.instantiate() as ShopItem
		$Control/Bg.add_child(shopItem)
		shopItem.position.y = 32 * count
		count += 1
		
		shopItem.init(itemResName, itemPrice)
		
		shopItem.onSelected.connect(onShopItemSelected)
		
		
func closeWeaponShop():
	$Control.modulate.a = 0
	

func onShopItemSelected(item):
	if $Control.modulate.a <= 0: return
	
	if Global.coin >= item.price:
		Global.coin -= item.price
		GlobalSignal.coinCollected.emit()
		closeWeaponShop()
		
		Global.createLoot(item.itemResName, merchant.global_position, get_tree().current_scene)


func _on_gui_input(event:InputEvent):
	if event.is_pressed():
		closeWeaponShop()
